﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Lk.WebTow.Authorize;
using Lk.WebTow.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;


namespace Lk.WebTow.Controllers
{
    public class AccountController : Controller
    {


        public AccountController()
        {
        }
        public IActionResult Login(string returnUrl)
        {

            ViewBag.ReturnUrl = returnUrl;
            return View();
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userName">用户ID</param>
        /// <param name="passWord">用户密码</param>
        /// <param name="rememberMe">是否记住密码</param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login(string userName, string passWord, string rememberMe)
        {

           var userModel= GetUserModels().FirstOrDefault(s=>s.UserName== userName&&s.Password== passWord);
            if(userModel==null)
            {
                 ModelState.AddModelError("","账号或者密码错误");
                return View();
            }
            var user = new ClaimsPrincipal(
             new ClaimsIdentity(new[]
             {
                        new Claim("UserName",userName),
                        new Claim("UserPwd",passWord),
                        new Claim("UserId",userModel.Id.ToString()),
             }, UserAuthorizeAttribute.UserAuthenticationScheme)
            );
            HttpContext.SignInAsync(UserAuthorizeAttribute.UserAuthenticationScheme, user, new AuthenticationProperties
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(60),// 有效时间
                //ExpiresUtc = DateTimeOffset.Now.Add(TimeSpan.FromDays(7)), // 有效时间
                IsPersistent = true,
                AllowRefresh = false
            });
            return new RedirectResult("~/Home/Index");//登录成功
        }


        private IEnumerable<UserModel> GetUserModels()
        {
            var result = new List<UserModel>() {
                new UserModel() {  UserName="test", Password="123456",Name="test",Id=1},
                new UserModel() { UserName = "test1", Password = "123456", Name = "test1",Id=2 } };

            return result;
        }
        public async Task<ActionResult> Register()
        {

            var dt = DateTime.Now;

            return View();
        }
    }
}